package com.itheima.day16.reflect.test3;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//        Constructor类用于创建对象的方法
public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        T newInstance(Object...initargs)	根据指定的构造方法创建对象
//        setAccessible(boolean flag)     	设置为true,表示取消访问检查

        // method1();
        // method2();
        // method3();
        // method4();


    }

    private static void method4() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 简写格式 [了解]
        // 1.获取class对象
        Class<?> className = Class.forName("com.itheima.day16.reflect.test3.Student");

        // 2.在Class类中，有一个newInstance方法，可以利用空参直接创建对象
        Student student = (Student) className.newInstance();

        System.out.println(student);
    }

    private static void method3() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 获取私有的带参构造方法并创建对象
        // 1.获取class对象
        Class<?> className = Class.forName("com.itheima.day16.reflect.test3.Student");

        // 2.获取构造方法
        Constructor<?> declaredConstructor = className.getDeclaredConstructor(String.class);

        // 3.取消访问检查
        declaredConstructor.setAccessible(true);

        // 4.获取对象
        Student student = (Student) declaredConstructor.newInstance("张帆");
        System.out.println(student);
    }

    private static void method2() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 获取一个公共的带参构造方法并创建对象
        // 1.获取class对象
        Class className = Student.class;

        // 2.获取构造方法
        Constructor declaredConstructor = className.getDeclaredConstructor(String.class, int.class);

        // 3.获取对象
        Student student = (Student) declaredConstructor.newInstance("张三", 23);

        System.out.println(student);
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 获取一个公共的无参构造方法并创建对象
        // 1.获取class对象
        Class className = Class.forName("com.itheima.day16.reflect.test3.Student");

        // 2.获取构造方法
        Constructor declaredConstructor = className.getDeclaredConstructor();

        // 3.获取对象
        Student student = (Student) declaredConstructor.newInstance();

        System.out.println(student);
    }
}
